//
//  HomeTableViewController.swift
//  SinaWeibo
//
//  Created by 郭平 on 15/9/30.
//  Copyright © 2015年 郭平. All rights reserved.
//

import UIKit
import SVProgressHUD


class HomeTableViewController: UITableViewController,popViewDelegate {

    var popView : PopView?
    
    lazy var statusArray: [StatusFrame] = [StatusFrame]()
    
    private let CELL_ID = "home_cell_id"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        visitorLoginView?.setUIInfo(imageName: "visitordiscover_feed_image_house", tipText: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        
        setupNav()
        // 设置tableView
        setupTableView()
    }
    
    private func setupTableView() {
        
        self.tableView.registerClass(StatusCell.self, forCellReuseIdentifier: CELL_ID)
        
        self.tableView.tableFooterView = pullupView
        
        
        // 下拉刷新的控件
        self.refreshControl = UIRefreshControl()
        self.refreshControl?.beginRefreshing()
        
        self.refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        loadData()
    }
    
    private func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.item("navigationbar_friendsearch", target: self, action: "push")
        navigationItem.rightBarButtonItem = UIBarButtonItem.item("navigationbar_pop", target: self, action: "push")
        
        setTitleButton()
    }
    
    private func setTitleButton() {
        
        let titleButton = HomeButton()
        
        titleButton.addTarget(self, action: "titleButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        titleButton.setTitle(UserAccount.loadUserAccount()?.name ?? "首页", forState: UIControlState.Normal)
        
        titleButton.setImage(UIImage(named: "navigationbar_arrow_down"), forState:UIControlState.Normal)
        titleButton.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Selected)
        
        titleButton.setTitleColor(RGB(r: 90, g: 90, b: 90), forState: UIControlState.Normal)
        
        titleButton.sizeToFit()
        navigationItem.titleView = titleButton
    }
    
    func titleButtonClick(button: UIButton) {
    
        button.selected = !button.selected
        
        let contentView = UIButton()
        contentView.setTitle("点我啊", forState: UIControlState.Normal)
        contentView.backgroundColor = UIColor.redColor()
        contentView.size = CGSizeMake(150, 150)
        contentView.addTarget(self, action: "coustomViewClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        let popView = PopView(customView: contentView)
        
        popView.delegate = self
        
        popView.show(button)
        self.popView = popView
    }
    
    // MARK: - popView的代理方法
    func popViewWillDismiss() {
        
        let button = navigationItem.titleView! as! UIButton
        button.selected = false
    }
    
    @objc private func coustomViewClick(button: UIButton) {
    
        self.popView!.dismiss()
    }
    
    @objc private func push() {
        
        let ctrl = TempViewController()
        navigationController?.pushViewController(ctrl, animated: true)
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // 获取数据
    @objc private func loadData() {
    
        let token = UserAccount.loadUserAccount()?.access_token
        
        var params = ["access_token" : token!]
        
        if pullupView.isAnimating() {
        
            if let status = statusArray.last {
                params["max_id"] = "\(status.status!.id - 1)"
            }
        }else{
            
            if let status = statusArray.first {
                
                params["since_id"] = "\(status.status!.id)"
            }
        }
        
        NetworkTools.shatedToos.loadData(params) { (dict, error) -> () in
            
//            printLog(dict)
            
            if let statusDics : [String : AnyObject] = dict {
                
                let dict = statusDics["statuses"] as? [[String : AnyObject]]
                
                var tempArray = [StatusFrame]()

                for statusDic in dict! {
                    let status = Status(dict: statusDic)
                    
                    let statusFrame = StatusFrame()
                    statusFrame.status = status
                    //往临时数组里面添加
                    tempArray.append(statusFrame)
                }
                
                // 判断是否上拉或下拉加载
                if self.pullupView.isAnimating() {

                    self.statusArray += tempArray
                
                }else {
                    self.statusArray = tempArray + self.statusArray
                    
                    if self.statusArray.count != 0 {
                        
                        self.showPullDownTips(tempArray.count)
                    }
                }
                
                self.tableView.reloadData()
            }
            
            self.endRefreshing()
            
            if error != nil {
                
                SVProgressHUD.showInfoWithStatus("请求失败,你的网络不好")
                
                self.endRefreshing()
            }
        }
    }
    
    // 结束刷新
    private func endRefreshing() {
        
        self.pullupView.stopAnimating()
        self.refreshControl?.endRefreshing()
    }
    
    private func showPullDownTips(count: Int){
        
        if pullDownTipLabel.hidden == false {
            return
        }
        
        pullDownTipLabel.text = count == 0 ? "没有新的微博" : "\(count)条新微博"
        
        let height: CGFloat = 35
        pullDownTipLabel.hidden = false
        
        pullDownTipLabel.size = CGSizeMake(SCREENW, height)
        pullDownTipLabel.y = CGRectGetMaxY(self.navigationController!.navigationBar.frame) - height
        
        UIView.animateWithDuration(1, animations: { () -> Void in
          
            self.pullDownTipLabel.transform = CGAffineTransformMakeTranslation(0, height)
            
            }) { (finish) -> Void in
                
                //执行回去的动画delay是代表当前动画延时xx秒之后才执行
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                 
                    self.pullDownTipLabel.transform = CGAffineTransformIdentity
                    
                    }, completion: { (finish) -> Void in
                        //动画执行完毕,隐藏
                        self.pullDownTipLabel.hidden = true
                })
        }
        
    }
    
    // MARK: - 懒加载
    // 下拉刷新提示的label
    private lazy var pullDownTipLabel: UILabel = {
    
        let label = UILabel()
        
        label.backgroundColor = UIColor.orangeColor()
        label.font = UIFont.systemFontOfSize(14)
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        label.text = "没有新的微博"
        
        self.navigationController?.view.insertSubview(label, belowSubview: self.navigationController!.navigationBar)
        
        label.hidden = true
        
        return label
    }()
    
    // 上拉加载的控件
    private lazy var pullupView: UIActivityIndicatorView = {
       
        let pullupView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        pullupView.color = UIColor.darkGrayColor()
        
        return pullupView
    }()
    

    
    
    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusArray.count
    }

    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID, forIndexPath: indexPath) as! StatusCell
        
        cell.statusFrame = statusArray[indexPath.row]
        
        if indexPath.row == statusArray.count - 1 && !pullupView.isAnimating() {
            
            pullupView.startAnimating()
            
            loadData()
        }
        
        return cell
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return statusArray[indexPath.row].cellHeight
    }
    

}
